# utils.py
import logging

import execjs
import time
import json

import mysql.connector

connection = mysql.connector.connect(
    host='192.168.220.131',
    database='eastmoney',
    user='root',
    password='123456'
)
cursor = connection.cursor()
def get_calback():
    """
    生成一个随机回调函数名。
    """
    js_code = """
        function get_callback(){
            return 'datatable' + Math.floor(Math.random() * 10000000 + 1)
        }
        get_callback()
    """
    ctx = execjs.compile(js_code)
    result = ctx.call("get_callback")
    return result

def parse_jsonp(jsonp_str):
    if isinstance(jsonp_str, dict):
        return jsonp_str

    try:
        start = jsonp_str.find('(') + 1
        end = jsonp_str.rfind(')')
        json_data = jsonp_str[start:end]
        data = json.loads(json_data)
        return data
    except Exception as e:
        logging.error(f"Failed to decode JSON: {e}")
        return None

def create_table(table_name):
    create_table_query = f"""
    CREATE TABLE IF NOT EXISTS `{table_name}` (
        `code` VARCHAR(255),
        `name` VARCHAR(255),
        `related_links` VARCHAR(255),
        `latest_price` VARCHAR(255),
        `price_change_percentage` VARCHAR(255),
        `price_change_amount` VARCHAR(255),
        `volume_hands` VARCHAR(255),
        `turnover_amount` VARCHAR(255),
        `amplitude` VARCHAR(255),
        `highest` VARCHAR(255),
        `lowest` VARCHAR(255),
        `opening_price` VARCHAR(255),
        `previous_close_price` VARCHAR(255),
        `turnover_rate` VARCHAR(255),
        `dynamic_pe_ratio` VARCHAR(255),
        `pb_ratio` VARCHAR(255)
    )
    """
    cursor.execute(create_table_query)